package timer

import (
	"time"
	"strconv"
	"dhfshop/models/misc"
	"github.com/astaxie/beego"
	"github.com/koangel/grapeTimer"
)

func NewGrapeTimer() {
	grapeTimer.InitGrapeScheduler(500*time.Microsecond, true)
	grapeTimer.CDebugMode = false
	grapeTimer.UseAsyncExec = true
}

type Callback func (payload int64) error

func AddTimerTask(mode int, date string, resItemId int64, callback Callback) (taskId int) {
	if mode == 1 {
	   standardDate := "Day " + date
	   taskId = grapeTimer.NewTimeDataOnce(standardDate, callback, resItemId)
	}
	taskJson := grapeTimer.ToJson(taskId)
	outerId := strconv.FormatInt(resItemId, 10)
	task := &misc.TimerTask{TaskId:int64(taskId), TaskBody:taskJson, OuterId:outerId}
	misc.AddTimerTask(task)
	return
}

func TaskList()(result map[int]string) {
	result = grapeTimer.List()
	return
}

func DelTimerTask(taskId int){
	grapeTimer.StopTimer(taskId)
	misc.DeleteTimerTaskByTaskId(int64(taskId))
	return
}

func LoadTaskFromDb(callback Callback)(result map[int]string) {
	if tasks, err := misc.GetAllTimerTasks(0, "", "", 0, 1000); err == nil {
	    for _, task := range tasks {
		    if outerId, err := strconv.ParseInt(task.OuterId, 10, 64); err == nil {
		       taskId := grapeTimer.NewFromJson(task.TaskBody, callback, outerId)
			   beego.Debug("oldtaskId:", task.TaskId, "newtaskId:", taskId)
			   m := &misc.TimerTask{Id:task.Id, TaskId:int64(taskId)}
			   misc.UpdateTimerTaskById(m, "task_id")
		    }
		}
	}
	return
}
